"""
xpath 是在 XML 文档中搜索内容的一门语言，html 是 xml 的一个子集。
亮点：可以在浏览器直接复制得到 xpath 路径。
安装 lxml 模块
    pip install lxml -i 镜像源仓库
"""
from lxml import etree

xml = '''
<book>
    <id>1</id>
    <name>野花遍地香</name>
    <price>1.23</price>
    <author>
        <nick>周大强</nick>
        <nick>周芷若</nick>
        <div>
            <nick>周芷若</nick>
            <div>
                <nick>周芷若</nick>
            </div>
        </div>
        <span>
            <nick>周芷若</nick>
        </span>
        <nick><div attr='da'>周大强</div></nick>
        <nick><div attr='xiao'>周芷若</div></nick>
    </author>
</book>
'''
etree_xml = etree.XML(xml)
name_content = etree_xml.xpath('/book/name/text()')  # text() 拿文本。
print(name_content)
author_content = etree_xml.xpath('/book/author/nick/text()')
print(author_content)
author_content = etree_xml.xpath('/book/author//nick/text()')  # //可以跳过中间多个层级。
print(author_content)
author_content = etree_xml.xpath('/book/author/*/nick/text()')  # *通配符，表示任意节点，类似于占位符。
print(author_content)
author_content = etree_xml.xpath('/book/author/nick[3]/div/text()')
print(author_content)
author_content = etree_xml.xpath('/book/author/nick[last()]/div/text()')
print(author_content)
author_content = etree_xml.xpath('/book/author/nick[last()-1]/div/text()')
print(author_content)
author_content = etree_xml.xpath('/book/author/nick[last()-1]/div/@attr')
print(author_content)
author_content = etree_xml.xpath('/book/author/nick[last()-1]/div/text() | /book/author/nick[last()-1]/div/@attr')
print(author_content)
author_content = etree_xml.xpath('/book/author/nick/div[@attr="xiao"]/text()')
print(author_content)
nick_node = etree_xml.xpath('/book/author/nick')
for node in nick_node:
    text = node.xpath('./div/text()')  # 相对路径
    if text:  # 如果 text 有值。
        print(text)
